package com.qk.management.controller;

import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.entity.User;
import com.qk.management.aop.annotation.LogAnno;
import com.qk.management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @DeleteMapping("/{ids}")
    public Result deleteByIds(@PathVariable String ids){
        String[] split = ids.split(",");
        for (String id : split) {
            userService.deleteUser(Integer.parseInt(id));
        }
        return Result.success();
    }

    @GetMapping
    public Result getUsers(UserDTO userDto) {
        PageResult<UserDO> pageResult = userService.list(userDto);
        return Result.success(pageResult);
    }

    @LogAnno
    @PostMapping
    public Result addUser(@RequestBody User user) {//RequestBody:把JSON数据转为User对象
        userService.addUser(user);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getUser(@PathVariable Integer id) {
        UserDO user = userService.getUser(id);
        return Result.success(user);
    }

    @LogAnno
    @PutMapping
    public Result updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return Result.success();
    }

    @GetMapping("/list")
    public Result list() {
        List<UserDO> users = userService.getAllUsers();
        return Result.success(users);
    }

    @GetMapping("/role/{roleLabel}")
    public Result listByRole(@PathVariable String roleLabel) {
        List<UserDO> users = userService.getUsersByRole(roleLabel);
        return Result.success(users);
    }

    @GetMapping("/dept/{deptId}")
    public Result listBydeptId(@PathVariable Integer deptId) {
        List<UserDO> users = userService.getUsersByDeptId(deptId);
        return Result.success(users);
    }

}
